
#include "DYSvrNetMan.h"
#include "stdio.h"

#include "TG_NET_TGL_DEF.h"

int DYSvrNetMan::TcpAudienceDispatch(SOCKET hClientSocket,NET_PACKET_HEAD *pMsgHead,BYTE *pBuffer)
{
	int nRet = TG_ERR_SUCCESS;

	char szRetBuffer[256];
	memset(szRetBuffer,0,sizeof(szRetBuffer));

	NET_PACKET_HEAD *pRetMsgHead = (NET_PACKET_HEAD*)szRetBuffer;
	pRetMsgHead->nMsgType = pMsgHead->nMsgType + 1;

	switch( pMsgHead->nMsgType )
	{
	case MSG_TYPE_GETANCHOR:
		{
			SendAllAnchorToUser(hClientSocket);
		}
		break;
	default:
		{
			nRet = TG_ERR_FAILURE;
		}
		break;
	}

	r_close( hClientSocket );
	hClientSocket = NULL;

	return nRet;
}

int DYSvrNetMan::UdpAudienceDispatch(SOCKET hSocket,TG_UDP_ADDR *pAddr,NET_PACKET_HEAD *pMsgHead,BYTE *pBuffer)
{
	int nRet = TG_ERR_SUCCESS;

	char szRetBuffer[256];
	memset(szRetBuffer,0,sizeof(szRetBuffer));

	NET_PACKET_HEAD *pRetMsgHead = (NET_PACKET_HEAD*)szRetBuffer;
	pRetMsgHead->nMsgType = pMsgHead->nMsgType + 1;


	switch( pMsgHead->nMsgType )
	{
	case MSG_TYPE_BROADCAST:
		{
		}
		break;
	default:
		{
			nRet = UdpAudienceCommand(hSocket,pAddr,pMsgHead,pBuffer);
		}
		break;
	}


	if( TG_ERR_SUCCESS != nRet )
	{
		pRetMsgHead->nFrameSize = 0;
		pRetMsgHead->nErrFlag   = nRet;

		sendto( hSocket,
			(char*)szRetBuffer,sizeof(NET_PACKET_HEAD),
			0,
			(struct sockaddr*)&pAddr->xAddr,pAddr->nAddrLen );
	}

	return nRet;
}

int DYSvrNetMan::UdpAudienceCommand(SOCKET hSocket,TG_UDP_ADDR *pAddr,NET_PACKET_HEAD *pMsgHead,BYTE *pBuffer)
{
	int nRet = TG_ERR_SUCCESS;

	switch( pMsgHead->nMsgType )
	{
	case MSG_TYPE_TGD_CLIENT_ALIVE:
	case MSG_TYPE_TGD_RETRANS_PACKET:
	case MSG_TYPE_TGD_CHANGE_NET_STATE:
		{

		}
		break;
	default:
		{
			nRet = TG_ERR_FAILURE;
			break;
		}
	}

	return nRet;
}

void DYSvrNetMan::SendAllAnchorToUser(SOCKET sock)
{
	int nCount = m_xSessionMan.GetSessionCount();
	UINT8* pAnchorList = NULL;
	DWORD dwRet = 0;
	if(nCount <= 0)
	{
		char szRetBuffer[256];
		memset(szRetBuffer,0,sizeof(szRetBuffer));

		NET_PACKET_HEAD *pRetMsgHead = (NET_PACKET_HEAD*)szRetBuffer;
		pRetMsgHead->nMsgType = MSG_TYPE_ANCHOR;
		pRetMsgHead->nFrameSize = 0;
		pRetMsgHead->SetCRC();

		send( sock,(char*)szRetBuffer,sizeof(NET_PACKET_HEAD),0 );

		return;
	}

	pAnchorList = new UINT8[sizeof(NET_PACKET_HEAD) + nCount * (TG_USERNAME_LEN + sizeof(DWORD))];
	m_xSessionMan.GetAnchorList(pAnchorList + sizeof(NET_PACKET_HEAD), nCount);
	
	NET_PACKET_HEAD *pRetMsgHead = (NET_PACKET_HEAD*)pAnchorList;
	pRetMsgHead->nMsgType = MSG_TYPE_ANCHOR;
	pRetMsgHead->nFrameSize = nCount * (TG_USERNAME_LEN + sizeof(DWORD));
	pRetMsgHead->SetCRC();

	send( sock,(char*)pAnchorList,sizeof(NET_PACKET_HEAD) + nCount * (TG_USERNAME_LEN + sizeof(DWORD)),0 );

	delete[] pAnchorList; pAnchorList = NULL;
}
